/*
 * @(#)UnionLoginService.java 1.0 2020/7/1
 *
 * Copyright (c) 2019 JDD. All rights reserved.
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.xyy.saas.payment.adpater.jdCredit.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jddglobal.open.client.DefaultHapiJddClient;
import com.jddglobal.open.client.HapiJddClient;
import com.jddglobal.open.support.util.JacksonUtils;
import com.xyy.saas.payment.cores.param.JdCreditUnionLoginParam;
import com.xyy.saas.payment.cores.vo.jd.JdCreditUnionLoginVo;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import com.jddglobal.open.support.app.*;
import java.util.HashMap;
import java.util.Map;
/**
 * TODO
 *
 * @author lixudong22
 * @version 1.0
 * @since 1.0
 */
@Service
@Slf4j
public class UnionLoginService {

    @Value("${open.public.key}")
    private String publicKey;
    @Value(("${open.private.key}"))
    private String privateKey;
    @Value("${open.md5Salt}")
    private String md5Salt;
    @Value("${open.sysId}")
    private String sysId;
    @Value("${open.token}")
    private String token;
    @Value("${open.openSys}")
    private String openSys;
    @Value("${open.processIdh5}")
    private String processIdH5;
    @Value("${open.processIdPc}")
    private String processIdPc;
    @Value("${open.url}")
    private String url;
    @Value("${open.encryptType}")
    private String encryptType;
    @Value("${open.signType}")
    private String signType;


    public JdCreditUnionLoginVo packingParams(JdCreditUnionLoginParam req) throws Exception {
        //标识外部平台ID 测试环境 生产
        log.info("packingParams param:{}",JSONObject.toJSONString(req));
        AppInfo appInfo = new AppInfo();
        appInfo.setAppId(openSys);
        appInfo.setJddKeyType(AppInfo.JddKeyTypeEnum.AKS);
        appInfo.setOpenPublicKey(publicKey);
        appInfo.setAppPrivateKey(privateKey);
        appInfo.setMd5Salt(md5Salt); //AKS不用盐值
        appInfo.setEncryptType(encryptType);
        appInfo.setSignType(signType);
        appInfo.setAppKeyType(AppInfo.AppKeyTypeEnum.PAIR);
        log.info(JSON.toJSONString(appInfo));
        Map<String, Object> data = new HashMap<>();
        Map systemInfo = new HashMap();
        //系统配置，分配
        systemInfo.put("sysId", sysId);
        systemInfo.put("token", token);
        data.put("systemInfo", systemInfo);

        Map<String, String> param = new HashMap<>();
        param.put("clientAgent", req.getClientAgent());
        JSONObject jsonObject = new JSONObject().fluentPut("backUrl", req.getBackUrl());
        if (StringUtils.isNotBlank(req.getOutCustNo())){
            //传入外部经销商编号
            jsonObject.fluentPut("outCustNo",req.getOutCustNo());
        }
        param.put("openApiParam", jsonObject.toJSONString());
        if (req.getLoginType().equals("H5")) {
            param.put("processId", processIdH5);
        } else if (req.getLoginType().equals("PC")) {
            param.put("processId", processIdPc);
        }

        param.put("openSys", openSys);
        param.put("openId", req.getThirdUserId());
        param.put("clientIp", req.getClientIp());
        param.put("openUser", req.getPlatformUserId());

        if (req.getLoginType().equals("H5")) {
            param.put("clientType", "h5");
        } else if (req.getLoginType().equals("PC")) {
            param.put("clientType", "PC");
        }
        data.put("param", param);
        log.info("packingParams data:{}",JSON.toJSONString(param));
        Map<String, Object> totalMap = new HashMap<>();
        totalMap.put("data", data);
        String jsonParams = JacksonUtils.toJson(totalMap);
        String requestTime = String.valueOf(System.currentTimeMillis());
        Pair<String, String> encryptAndSign = gainEncryptAndSign(jsonParams, appInfo, requestTime);
        JdCreditUnionLoginVo result = new JdCreditUnionLoginVo();
        result.setEncrypt(encryptAndSign.getKey());
        result.setSign(encryptAndSign.getValue());
        result.setTime(requestTime);
        result.setUserId(appInfo.getAppId());
        result.setOpenUrl(url);
        result.setGwSignType(signType);
        result.setGwEncryptType(encryptType);
        return result;
    }

    private static Pair<String, String> gainEncryptAndSign(String jsonParams, AppInfo appInfo, String requestTime) throws Exception {
        HapiJddClient hapiJddClient = new DefaultHapiJddClient(appInfo);
        String[] args = hapiJddClient.gainEncryptAndSign(jsonParams, requestTime);
        return new Pair<>(args[0], args[1]);
    }

}
